package com.changgou.goods.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.goods.dao.*;
import com.changgou.goods.pojo.*;
import com.changgou.goods.service.SpuService;
import com.changgou.util.IdWorker;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class SpuServiceImpl implements SpuService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private SpuMapper spuMapper;
    @Autowired
    private SkuMapper skuMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private BrandMapper brandMapper;
    @Autowired
    private CategoryBrandMapper categoryBrandMapper;

    @Autowired
    private IdWorker idWorker;

    /**
     * 查询全部列表
     * @return
     */
    @Override
    public List<Spu> findAll() {
        return spuMapper.selectAll();
    }

    /**
     * 根据ID查询
     * @param id
     * @return
     */
    @Override
    public Spu findById(String id){
        return  spuMapper.selectByPrimaryKey(id);
    }


    /**
     * 增加
     * @param spu
     */
    @Override
    public void add(Spu spu){
        spuMapper.insert(spu);
    }


    /**
     * 修改
     * @param spu
     */
    @Override
    public void update(Spu spu){
        spuMapper.updateByPrimaryKey(spu);
    }

    /**
     * 删除
     * @param id
     */
    @Override
    public void delete(String id){
        spuMapper.deleteByPrimaryKey(id);
    }


    /**
     * 条件查询
     * @param searchMap
     * @return
     */
    @Override
    public List<Spu> findList(Map<String, Object> searchMap){
        Example example = createExample(searchMap);
        return spuMapper.selectByExample(example);
    }

    /**
     * 分页查询
     * @param page
     * @param size
     * @return
     */
    @Override
    public Page<Spu> findPage(int page, int size){
        PageHelper.startPage(page,size);
        return (Page<Spu>)spuMapper.selectAll();
    }

    /**
     * 条件+分页查询
     * @param searchMap 查询条件
     * @param page 页码
     * @param size 页大小
     * @return 分页结果
     */
    @Override
    public Page<Spu> findPage(Map<String,Object> searchMap, int page, int size){
        PageHelper.startPage(page,size);
        Example example = createExample(searchMap);
        return (Page<Spu>)spuMapper.selectByExample(example);
    }

    /**
     * @Date: 10:10 2020/5/14
     * @Param: [goods]
     * @return: com.changgou.entity.Result
     * @Description: 商品新增
     **/
    @Override
    @Transactional //事务注解
    public void addGoods(Goods goods) {
        //1.获取spu
        Spu spu = goods.getSpu();
        //2.通过idwork 设置spu id
        spu.setId(String.valueOf(idWorker.nextId()));
        //3.新增spu
        spuMapper.insertSelective(spu);
        //4.新增skuList
        saveSkuList(goods);
    }

    /**
     * @Date: 11:19 2020/5/14
     * @Param: [spuId]
     * @return: com.changgou.entity.Result
     * @Description: 根虎spuId查询商品(goods)列表
     *
     * @param spuId*/
    @Override
    public Goods findGoodsBySpuId(String spuId) {
        Goods goods = new Goods();
        Spu spu = spuMapper.selectByPrimaryKey(spuId);
        goods.setSpu(spu);
        if(null != spu){
            Example example = new Example(Sku.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("spuId", spuId);
            //select * from tb_sku where spu_id = spuId
            List<Sku> skuList = skuMapper.selectByExample(example);
            goods.setSkuList(skuList);
        }
        return goods;
    }

    /**
     * @Date: 11:34 2020/5/14
     * @Param: [goods]
     * @return: com.changgou.entity.Result
     * @Description: 商品更新操作
     **/
    @Override
    public void updateByGoods(Goods goods) {
        //1.更新spu--->根据主键
        Spu spu = goods.getSpu();
        spuMapper.updateByPrimaryKeySelective(spu);
        //2.删除skuList --->根据spuId
        Example example = new Example(Sku.class); //拼接sql时告知执行的是那张表
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("spuId", spu.getId());
        int i = skuMapper.deleteByExample(example);
        logger.info("删除sku个数： {}", i);
        //3.调用共有保存skuList方法
        saveSkuList(goods);

    }

    /**
     * @Date: 11:49 2020/5/14
     * @Param: [id]
     * @return: com.changgou.entity.Result
     * @Description: 审核商品
     **/
    @Override
    public void auditGoods(String id) {
        Spu spu = new Spu();
        spu.setId(id);
        spu.setStatus("1"); //审核通过
        spuMapper.updateByPrimaryKeySelective(spu);
    }

    /**
     * @Date: 11:54 2020/5/14
     * @Param: [id]
     * @return: com.changgou.entity.Result
     * @Description: 商品上架
     **/
    @Override
    public void pushGoods(String id) {
        //select * from tb_spu where id = 123
        Spu spu = spuMapper.selectByPrimaryKey(id);
        //1.判断spu是否为null
        //2.判断spu中的审核状态是否为1（审核通过）
        String status = spu.getStatus();
        if(!"1".equals(status)){
            //3.如果不是1则抛出运行时异常---》未审核商品不能上架
            new RuntimeException("未审核商品不能上架");
        }
        //4.将商品上架
       /* spu.setIsMarketable("1"); //上架


        //update tb_spu set id =  ...... where id =123
        spuMapper.updateByPrimaryKeySelective(spu); //相当于全参拼接sql
*/
        //-------优化后
        //update tb_spu set is_marktable=1 where id =123
        Spu spu1 = new Spu();
        spu1.setId(id);
        spu1.setIsMarketable("1"); //上架
        //update tb_spu set is_marktable=1 where id =123
        spuMapper.updateByPrimaryKeySelective(spu1); //相当于是有值拼接
    }

    /**
     * @Date: 14:04 2020/5/14
     * @Param: [id]
     * @return: com.changgou.entity.Result
     * @Description: 商品下架
     **/
    @Override
    public void downGoods(String id) {
        //1.根据id查询spu
        Spu spu = spuMapper.selectByPrimaryKey(id);
        //2.将上架状态设置为0(下架)
        spu.setIsMarketable("0"); //设置为下架
        //3.更新
        //TODO: 存在代码优化点
        spuMapper.updateByPrimaryKeySelective(spu);
    }

    /**
     * @Date: 14:17 2020/5/14
     * @Param: [id]
     * @return: com.changgou.entity.Result
     * @Description: 将商品删除到回收站
     **/
    @Override
    public void deleteLogic(String id) {
        Spu spu = spuMapper.selectByPrimaryKey(id);
        //1.判断商品是否下架
        if("1".equals(spu.getIsMarketable())){ //代表商品是上架状态
            throw new RuntimeException("已上架商品不可以删除，请先下架");
        }else {
            //2.下架状态则删除---》is_delete=1 and status=0
            spu.setIsDelete("1"); //删除状态
            spu.setStatus("0"); //设置为未审核状态
            //TODO: 存在代码优化点
            spuMapper.updateByPrimaryKeySelective(spu);
        }
    }

    /**
     * @Date: 14:25 2020/5/14
     * @Param: [id]
     * @return: com.changgou.entity.Result
     * @Description: 还原商品
     **/
    @Override
    public void restore(String id) {
        Spu spu = spuMapper.selectByPrimaryKey(id);
        //1.先判断是否有逻辑删除
        if("0".equals(spu.getIsDelete())){ //未删除
            //2.没有删除则抛出运行时异常----》未删除商品不需要还原
            throw new RuntimeException("未删除商品不需要还原");
        }else {
            //3.删除状态---》则设置为未删除
            spu.setIsDelete("0");
            //4.设置审核状态为未审核
            spu.setStatus("0");
            //TODO: 存在代码优化点
            spuMapper.updateByPrimaryKeySelective(spu);
        }
    }

    /**
     * @Date: 14:33 2020/5/14
     * @Param: [id]
     * @return: com.changgou.entity.Result
     * @Description: 物理删除商品
     **/
    @Override
    public void deleteGoods(String id) {
        Spu spu = spuMapper.selectByPrimaryKey(id);
        //1.判断商品是否被逻辑删除
        if("0".equals(spu.getIsDelete())){ //未删除
            //2.如果没有被逻辑删除---》抛异常 请将商品先放入回收站
            throw new RuntimeException("请将商品先放入回收站");
        }else {
            //3.如果逻辑删除成功---》直接物理删除
            spuMapper.deleteByPrimaryKey(id);
        }
    }

    /**
    * @Date: 10:18 2020/5/14
    * @Param: [goods]
    * @return: void
    * @Description: 保存skuList
    **/
    private void saveSkuList(Goods goods) {
        //1.获取skuList
        List<Sku> skuList = goods.getSkuList();
        Spu spu = goods.getSpu();
        //2.对skuList判空
        if(!CollectionUtils.isEmpty(skuList)){
            //获取分类对象
            Category category = categoryMapper.selectByPrimaryKey(spu.getCategory3Id());
            //获取品牌对象
            Brand brand = brandMapper.selectByPrimaryKey(spu.getBrandId());
            //需要维护品牌分类中间表
            if(null != category && null != brand){
                CategoryBrand categoryBrand = new CategoryBrand();
                categoryBrand.setCategoryId(category.getId());
                categoryBrand.setBrandId(brand.getId());
                //select count(*) from tb_category_brand where categoryId = and brandId=
                int i = categoryBrandMapper.selectCount(categoryBrand);
                if(0 == i){
                    categoryBrandMapper.insertSelective(categoryBrand);
                }
            }
            //3.遍历skuList
            for (Sku sku : skuList) {
                //4.设置id
                sku.setId(String.valueOf(idWorker.nextId()));
                String spec = sku.getSpec();
                //spec必须为json格式，防止下面json解析异常
                if(StringUtils.isEmpty(spec)){
                    spec = "{}";
                    sku.setSpec(spec);
                }
                //5.设置name
                // 华为 HUAWEI P40 Pro 麒麟990 5G SoC芯片 5000万超感知徕卡四摄 50倍数字变焦 8GB+256GB晨曦金全网通5G手机
                //spuName+规格列表(sku)
                StringBuilder skuNameBuilder = new StringBuilder();
                skuNameBuilder.append(spu.getName());
                //String skuName = spu.getName();
                //{"颜色":"红色","内存":"4g"}
                Map<String, String> specMap = JSON.parseObject(spec, Map.class);
                for (Map.Entry<String, String> entry : specMap.entrySet()) {
                    String specVal = entry.getValue();
                    //skuName += " "
                    skuNameBuilder.append(" ");
                    skuNameBuilder.append(specVal);
                }
                sku.setName(skuNameBuilder.toString());
                //6.创建时间
                sku.setCreateTime(new Date());
                //7.更新时间
                sku.setUpdateTime(new Date());
                //8.设置spuId
                sku.setSpuId(spu.getId());
                if(null != category){
                    //9.设置分类id--->三级分类id
                    sku.setCategoryId(category.getId());
                    //10.设置分类名称
                    sku.setCategoryName(category.getName());
                }
                if(null != brand){
                    //11.设置品牌名称
                    sku.setBrandName(brand.getName());
                }
                //12.新增sku
                skuMapper.insertSelective(sku);
            }
        }
    }

    /**
     * 构建查询对象
     * @param searchMap
     * @return
     */
    private Example createExample(Map<String, Object> searchMap){
        Example example=new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        if(searchMap!=null){
            // 主键
            if(searchMap.get("id")!=null && !"".equals(searchMap.get("id"))){
                criteria.andEqualTo("id",searchMap.get("id"));
           	}
            // 货号
            if(searchMap.get("sn")!=null && !"".equals(searchMap.get("sn"))){
                criteria.andEqualTo("sn",searchMap.get("sn"));
           	}
            // SPU名
            if(searchMap.get("name")!=null && !"".equals(searchMap.get("name"))){
                criteria.andLike("name","%"+searchMap.get("name")+"%");
           	}
            // 副标题
            if(searchMap.get("caption")!=null && !"".equals(searchMap.get("caption"))){
                criteria.andLike("caption","%"+searchMap.get("caption")+"%");
           	}
            // 图片
            if(searchMap.get("image")!=null && !"".equals(searchMap.get("image"))){
                criteria.andLike("image","%"+searchMap.get("image")+"%");
           	}
            // 图片列表
            if(searchMap.get("images")!=null && !"".equals(searchMap.get("images"))){
                criteria.andLike("images","%"+searchMap.get("images")+"%");
           	}
            // 售后服务
            if(searchMap.get("saleService")!=null && !"".equals(searchMap.get("saleService"))){
                criteria.andLike("saleService","%"+searchMap.get("saleService")+"%");
           	}
            // 介绍
            if(searchMap.get("introduction")!=null && !"".equals(searchMap.get("introduction"))){
                criteria.andLike("introduction","%"+searchMap.get("introduction")+"%");
           	}
            // 规格列表
            if(searchMap.get("specItems")!=null && !"".equals(searchMap.get("specItems"))){
                criteria.andLike("specItems","%"+searchMap.get("specItems")+"%");
           	}
            // 参数列表
            if(searchMap.get("paraItems")!=null && !"".equals(searchMap.get("paraItems"))){
                criteria.andLike("paraItems","%"+searchMap.get("paraItems")+"%");
           	}
            // 是否上架
            if(searchMap.get("isMarketable")!=null && !"".equals(searchMap.get("isMarketable"))){
                criteria.andEqualTo("isMarketable",searchMap.get("isMarketable"));
           	}
            // 是否启用规格
            if(searchMap.get("isEnableSpec")!=null && !"".equals(searchMap.get("isEnableSpec"))){
                criteria.andEqualTo("isEnableSpec", searchMap.get("isEnableSpec"));
           	}
            // 是否删除
            if(searchMap.get("isDelete")!=null && !"".equals(searchMap.get("isDelete"))){
                criteria.andEqualTo("isDelete",searchMap.get("isDelete"));
           	}
            // 审核状态
            if(searchMap.get("status")!=null && !"".equals(searchMap.get("status"))){
                criteria.andEqualTo("status",searchMap.get("status"));
           	}

            // 品牌ID
            if(searchMap.get("brandId")!=null ){
                criteria.andEqualTo("brandId",searchMap.get("brandId"));
            }
            // 一级分类
            if(searchMap.get("category1Id")!=null ){
                criteria.andEqualTo("category1Id",searchMap.get("category1Id"));
            }
            // 二级分类
            if(searchMap.get("category2Id")!=null ){
                criteria.andEqualTo("category2Id",searchMap.get("category2Id"));
            }
            // 三级分类
            if(searchMap.get("category3Id")!=null ){
                criteria.andEqualTo("category3Id",searchMap.get("category3Id"));
            }
            // 模板ID
            if(searchMap.get("templateId")!=null ){
                criteria.andEqualTo("templateId",searchMap.get("templateId"));
            }
            // 运费模板id
            if(searchMap.get("freightId")!=null ){
                criteria.andEqualTo("freightId",searchMap.get("freightId"));
            }
            // 销量
            if(searchMap.get("saleNum")!=null ){
                criteria.andEqualTo("saleNum",searchMap.get("saleNum"));
            }
            // 评论数
            if(searchMap.get("commentNum")!=null ){
                criteria.andEqualTo("commentNum",searchMap.get("commentNum"));
            }

        }
        return example;
    }

}
